# -*- coding:utf-8 -*-
import uuid

from typing import Optional, ClassVar, Union
from enum import Enum

from redis import Redis
from sqlmodel import SQLModel, Field
from redis_om import HashModel


class StorageMode(Enum):
    SQL = "sql"
    REDIS = "redis"
    HYBRID = "hybrid"


class OrmModel(SQLModel, HashModel):
    """支持 SQL + Redis 双存储的模型基类"""
    __storage_mode__: ClassVar[StorageMode] = StorageMode.HYBRID
    __redis_key_prefix__: ClassVar[str] = "hybrid"
    __redis_ttl__: ClassVar[Optional[int]] = None
    # 添加类属性存储 Redis 连接
    __redis_conn__: ClassVar[Optional[Redis]] = None

    @classmethod
    def set_redis_connection(cls, conn: Redis):
        """设置模型类级别的 Redis 连接"""
        cls.__redis_conn__ = conn

    # 主键需兼容两种存储
    id: Optional[Union[int, str]] = Field(
        default=None,
        primary_key=True,
        description="SQL使用自增整数，Redis使用UUID字符串"
    )

    def __init__(self, **data):
        # Redis模式自动生成字符串ID
        if self.__storage_mode__ == StorageMode.REDIS and 'id' not in data:
            data['id'] = f"{self.__class__.__name__.lower()}_{uuid.uuid4().hex}"
        super().__init__(**data)

    def redis_key(self) -> str:
        return f"{self.__redis_key_prefix__}:{self.__class__.__name__}:{self.id}"
